package com.example.pathtracker.utils

import android.content.Context
import android.os.Handler
import android.os.Looper
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.model.LatLng

class LocationManager private constructor(private val context: Context) {
    private var locationClient: AMapLocationClient? = null
    private var locationListener: AMapLocationListener? = null
    private var isTracking = false
    private val handler = Handler(Looper.getMainLooper())
    private val pathPoints = mutableListOf<LatLng>()
    private var onLocationUpdateListener: ((AMapLocation) -> Unit)? = null
    private var onPathUpdateListener: ((List<LatLng>) -> Unit)? = null
    private var isInitialized = false

    companion object {
        @Volatile
        private var INSTANCE: LocationManager? = null

        fun getInstance(context: Context): LocationManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: LocationManager(context.applicationContext).also { INSTANCE = it }
            }
        }
    }

    fun initLocation() {
        try {
            locationClient = AMapLocationClient(context)
            locationClient?.setLocationListener(object : AMapLocationListener {
                override fun onLocationChanged(location: AMapLocation?) {
                    location?.let { handleLocationUpdate(it) }
                }
            })

            val locationOption = AMapLocationClientOption().apply {
                locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
                interval = 1000
                isNeedAddress = true
                isMockEnable = false
                httpTimeOut = 20000
                isLocationCacheEnable = false
                isSensorEnable = true
                isGpsFirst = true
                isOnceLocationLatest = false
                isOnceLocation = false
            }
            locationClient?.setLocationOption(locationOption)
            isInitialized = true
        } catch (e: Exception) {
            android.util.Log.e("LocationManager", "初始化失败", e)
            isInitialized = false
        }
    }

    fun isInitialized(): Boolean = isInitialized

    fun setLocationInterval(interval: Long) {
        try {


            locationClient?.setLocationOption(AMapLocationClientOption().apply {
                this.interval = interval
            })


        } catch (e: Exception) {
            android.util.Log.e("LocationManager", "设置定位间隔失败", e)
        }
    }

    fun setLocationFastestInterval(interval: Long) {
        try {
            locationClient?.setLocationOption(AMapLocationClientOption().apply {
                this.httpTimeOut = interval
            })


        } catch (e: Exception) {
            android.util.Log.e("LocationManager", "设置最快定位间隔失败", e)
        }
    }

    fun requestSingleUpdate() {
        try {


            locationClient?.setLocationOption(AMapLocationClientOption().apply {
                isOnceLocation = true
            })

            locationClient?.startLocation()
            
            // 重置为连续定位模式
            handler.postDelayed({
                locationClient?.setLocationOption(AMapLocationClientOption().apply {
                    isOnceLocation = false
                })
            }, 5000)

        } catch (e: Exception) {
            android.util.Log.e("LocationManager", "请求单次定位失败", e)
        }
    }

    private fun handleLocationUpdate(location: AMapLocation) {
        if (location.errorCode == 0) {
            val latLng = LatLng(location.latitude, location.longitude)
            
            // 总是通知位置更新
            onLocationUpdateListener?.invoke(location)
            
            if (isTracking) {
                // 降低精度要求，从20米改为50米
                if (LocationUtils.isAccuracyValid(location.accuracy, 50f)) {
                    // 降低距离阈值，从2米改为1米
                    if (pathPoints.isEmpty() || 
                        LocationUtils.calculateDistance(pathPoints.last(), latLng) >= 1.0) {
                        pathPoints.add(latLng)
                        onPathUpdateListener?.invoke(pathPoints.toList())
                        
                        // 调试信息
                        android.util.Log.d("LocationManager", "添加路径点: ${latLng.latitude}, ${latLng.longitude}, 精度: ${location.accuracy}米, 总点数: ${pathPoints.size}")
                    }
                } else {
                    android.util.Log.d("LocationManager", "精度不满足要求: ${location.accuracy}米")
                }
            }
        } else {
            android.util.Log.e("LocationManager", "定位失败: ${location.errorInfo}")
        }
    }

    fun startTracking() {
        isTracking = true
        pathPoints.clear()
        try {
            locationClient?.startLocation()
        } catch (e: Exception) {
            android.util.Log.e("LocationManager", "开始跟踪失败", e)
        }
    }

    fun stopTracking() {
        isTracking = false
        try {
            locationClient?.stopLocation()
        } catch (e: Exception) {
            android.util.Log.e("LocationManager", "停止跟踪失败", e)
        }
    }

    fun getPathPoints(): List<LatLng> = pathPoints.toList()

    fun clearPath() {
        pathPoints.clear()
        onPathUpdateListener?.invoke(emptyList())
    }

    fun setOnLocationUpdateListener(listener: (AMapLocation) -> Unit) {
        onLocationUpdateListener = listener
    }

    fun setOnPathUpdateListener(listener: (List<LatLng>) -> Unit) {
        onPathUpdateListener = listener
    }

    fun destroy() {
        try {
            locationClient?.onDestroy()
            locationClient = null
            handler.removeCallbacksAndMessages(null)
            isInitialized = false
        } catch (e: Exception) {
            android.util.Log.e("LocationManager", "销毁失败", e)
        }
    }
} 